﻿using FastCode.DTO;
using FastCode.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Reflection;

namespace FastCode.Architecture
{

    [ApiController]
    [Route("api/[controller]/[action]")]
    public class ApiControllerBase<TEntity> : ControllerBase where TEntity : BaseModel, new()
    {
        public SqlSugarClient db = SqlSugarHelper.Db;


        public ISugarQueryable<BEntity> GetBaseQuery<BEntity>() where BEntity : BaseModel
        {
            return db.Queryable<BEntity>().Where(x => !x.IsDeleted);
        }


        [HttpPost]
        public virtual async Task<object> List([FromBody] QueryBase queryBase)
        {
            RefAsync<int> totalNumber = 0;
            var query = db.Queryable<TEntity>().Where(x => !x.IsDeleted);

            // 解析 SearchCondition 并构建查询条件
            if (queryBase.SearchConditions != null && queryBase.SearchConditions.Any())
            {
                //var searchConditions = JsonConvert.DeserializeObject<List<SearchCondition>>(queryBase.SearchCondition);
                foreach (var condition in queryBase.SearchConditions)
                {
                    var value = condition.Value.ToString();
                    if (string.IsNullOrEmpty(value))
                    {
                        continue;
                    }
                    switch (condition.ConditionType)
                    {
                        case ConditionType.Equal:
                            //query = query.Where($"{condition.FieldName} == @Value", new { condition.Value });
                            query = query.Where($"{condition.FieldName}=@{condition.FieldName}", new Dictionary<string, object> { { condition.FieldName, $"{condition.Value}" } });

                            //query = query.Where($"{condition.FieldName} == {}", condition.Value);
                            break;
                        case ConditionType.Contains:
                            var valusstr = condition.Value.ToString();

                            query = query.Where($"{condition.FieldName} LIKE @{condition.FieldName}", new Dictionary<string, object> { { condition.FieldName, $"%{condition.Value}%" } });
                            break;
                    }
                }
            }
            var list = await query.ToPageListAsync(queryBase.pageIndex, queryBase.pageSize, totalNumber);

            var columnNames = new List<ColumnConfig>();
            //获取并返回对象的所有属性名
            Type entityType = typeof(TEntity);
            PropertyInfo[] properties = entityType.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                var controlTypeAttribute = property.GetCustomAttribute<UITypeAttribute>();
                var colItem = new ColumnConfig
                {
                    Name = property.Name,
                    Order = 100,
                    Label = property.Name,
                    ControlType = EUIType.Text,
                    IsShow = true,
                    IsEditable = true,
                    TypeName = property.PropertyType.Name
                };

                if (controlTypeAttribute != null)
                {
                    var attColName = controlTypeAttribute.ColumnConfig;
                    colItem.ControlType = attColName.ControlType;
                    if (!string.IsNullOrEmpty(attColName.Label))
                    {
                        colItem.Label = attColName.Label;
                    }
                    colItem.Order = attColName.Order;
                    colItem.IsShow = attColName.IsShow;
                    colItem.IsEditable = attColName.IsEditable;
                }
                //如果是枚举
                if (property.PropertyType.IsEnum)
                {
                    colItem.ControlType = EUIType.Enum;
                    colItem.EnumDic = EnumToDictionary(property.PropertyType);
                }
                if (colItem.IsShow)
                {
                    columnNames.Add(colItem);
                }
            }

            return Msg.Success(new { list, columnNames = columnNames.OrderBy(x => x.Order), totalNumber = totalNumber.Value });
        }


        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<object> GetAllData()
        {
            var query = GetBaseQuery<TEntity>();
            var list = await query.ToListAsync();
            return Msg.Success(list);
        }

        static Dictionary<int, string> EnumToDictionary(Type type)
        {
            var enumDict = new Dictionary<int, string>();
            foreach (var value in Enum.GetValues(type))
            {
                enumDict.Add((int)value, value.ToString());
            }
            return enumDict;
        }

        [HttpPost]
        public async Task<object> DelById([FromBody] TEntity query)
        {
            var findItem = await db.Queryable<TEntity>().FirstAsync(x => x.Id == query.Id);

            return Msg.Success(findItem);
        }


        [HttpPost]
        public async Task<object> GetById([FromBody] TEntity query)
        {
            var findItem = await db.Queryable<TEntity>().FirstAsync(x => x.Id == query.Id);

            return Msg.Success(findItem);
        }

        [HttpPost]
        public async Task<object> Update([FromBody] TEntity entity)
        {

            var nowTime = DateTime.Now;
            if (entity.Id == 0)
            {
                //时间
                entity.CreateTime = nowTime;
                await db.Insertable(entity).ExecuteCommandAsync();
                return Msg.Success(message: "新增成功");

            }
            else
            {
                entity.UpdateTime = nowTime;
                await db.Updateable(entity).ExecuteCommandAsync();
                return Msg.Success(message: "更新成功");
            }
        }
    }
}
